#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import http.server
import socketserver
import json
import webbrowser
from datetime import datetime
import sys

# 城市列表
CITIES = [
    '北京', '上海', '广州', '深圳', '成都', '重庆', '西安', '武汉',
    '南京', '杭州', '天津', '青岛', '厦门', '长沙', '郑州', '合肥',
    '济南', '福州', '南昌', '石家庄', '太原', '呼和浩特', '沈阳', '大连',
    '长春', '哈尔滨', '昆明', '贵阳', '南宁', '海口', '三亚', '兰州',
    '西宁', '银川', '乌鲁木齐', '拉萨', '池州', '东至', '东至县'
]

class DebugHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def log_message(self, format, *args):
        """重写日志方法，输出到控制台"""
        print(f"[{datetime.now().strftime('%H:%M:%S')}] {format % args}")
    
    def do_GET(self):
        print(f"🔍 GET请求: {self.path}")
        
        if self.path == '/':
            self.path = '/frontend/index.html'
            print("  📄 重定向到前端页面")
        elif self.path == '/api/status':
            print("  📊 处理状态API请求")
            self.send_api_status()
            return
        elif self.path == '/api/cities':
            print("  🏙️ 处理城市API请求")
            self.send_cities()
            return
        else:
            print(f"  📁 静态文件: {self.path}")
        
        super().do_GET()
    
    def do_OPTIONS(self):
        print("🔍 OPTIONS请求")
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
    
    def send_api_status(self):
        """发送API状态"""
        print("  📊 发送API状态")
        status = {
            'success': True,
            'status': 'success',
            'message': '调试服务器运行正常',
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'features': [
                '🌍 全国城市支持',
                '⚡ 快速响应',
                '🎯 支持小城市',
                '🔧 调试模式'
            ],
            'debug': {
                'server_port': PORT,
                'cities_count': len(CITIES),
                'python_version': sys.version
            }
        }
        self.send_json_response(status)
    
    def send_cities(self):
        """发送城市列表"""
        print(f"  🏙️ 发送城市列表，共{len(CITIES)}个城市")
        self.send_json_response({
            'success': True,
            'cities': CITIES,
            'count': len(CITIES),
            'debug': {
                'has_dalian': '大连' in CITIES,
                'has_dongzhi': '东至' in CITIES,
                'has_dongzhi_county': '东至县' in CITIES
            }
        })
    
    def send_json_response(self, data):
        print(f"  📤 发送JSON响应: {json.dumps(data, ensure_ascii=False)[:100]}...")
        self.send_response(200)
        self.send_header('Content-type', 'application/json; charset=utf-8')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
        
        json_data = json.dumps(data, ensure_ascii=False, indent=2)
        self.wfile.write(json_data.encode('utf-8'))

if __name__ == '__main__':
    PORT = 5002
    
    print("=" * 60)
    print(" 启动调试服务器")
    print("=" * 60)
    print(f"服务地址: http://localhost:{PORT}")
    print(f"前端页面: http://localhost:{PORT}/frontend/index.html")
    print(f"状态API: http://localhost:{PORT}/api/status")
    print(f"城市API: http://localhost:{PORT}/api/cities")
    print("=" * 60)
    print("特性:")
    print("- 详细日志输出")
    print("- 全国城市支持")
    print("- 包含东至等小城市")
    print("- 调试信息")
    print("=" * 60)
    print("按 Ctrl+C 停止服务")
    print("=" * 60)
    
    try:
        try:
            webbrowser.open(f"http://localhost:{PORT}/frontend/index.html")
        except Exception as e:
            print(f"⚠️ 无法自动打开浏览器: {e}")
        
        with socketserver.TCPServer(("", PORT), DebugHTTPRequestHandler) as httpd:
            print(f"✅ 服务器启动成功，监听端口 {PORT}")
            print("🔍 等待请求...")
            httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n🛑 服务器已停止")
    except Exception as e:
        print(f"❌ 服务器启动失败: {e}")
        print("💡 可能的原因:")
        print("  1. 端口被占用")
        print("  2. 权限不足")
        print("  3. 防火墙阻止")